<?php
// +----------------------------------------------------------------------
// | 管理员相关操作
// +----------------------------------------------------------------------
// | @link ( http://www.yurnero.net )
// +----------------------------------------------------------------------
// | @copyright
// +----------------------------------------------------------------------
// | @licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | @author Haijun Wu <nicholasinlove@126.com>
// +----------------------------------------------------------------------
// | $Id: AdminAction.class.php 121 2011-05-17 10:03:49Z nicholasinlove1986@gmail.com $
// +----------------------------------------------------------------------


class AdminAction extends Action {

	//初始化接口
	public function _initialize() {	
	
		/* 对用户传入的变量进行去除转义操作。*/
		all_stripslashes();
		
		/* 载入系统参数 */
		global $_CFG; 
		$_CFG = get_config();	
	}
	
	public function index() {
		redirect(__APP__);
	}
	
	//检查用户是否登录
	protected function checkUser() {
		if (!isset($_SESSION[C('USER_AUTH_KEY')])) {
			$this->assign('jumpUrl',__APP__.'/Admin/login/');
			$this->error(L('login_first'));
		}
	}
	
	//检查权限
	protected function checkLimits() {
		if ($_SESSION['user_level'] != 0) {
			$this->error(L('no_limits'));
		}
	}
		
	//登录界面
	public function login() {
		C ('SHOW_RUN_TIME', false);
		C ('SHOW_PAGE_TRACE', false);
		unset($_SESSION);
		session_destroy();
		$this->display();
	}
	
	//用户登出
	public function logout() {
		if (isset($_SESSION[C('USER_AUTH_KEY')])) {
			set_log('logout(System)');
			unset($_SESSION[C('USER_AUTH_KEY')]);
			unset($_SESSION);
			session_destroy();
			$this->assign('jumpUrl',__URL__.'/login/');
			$this->success(L('logout'));
		} else {
			$this->assign('jumpUrl',__URL__.'/login/');
			$this->error(L('logout_'));
		}
	}
	
	//登录检测
	public function checkLogin() {
		$admin = M('AdminUser');
		if (empty($_POST['user_name'])) {
			$this->error(L('no_blank'));
		} elseif (empty($_POST['user_password'])) {
			$this->error(L('no_blank'));
		} elseif (empty($_POST['verify'])) {
			$this->error(L('no_blank'));
		}
		if ($_SESSION['verify'] != md5($_POST['verify'])) {
			$this->error(L('wrong_code'));
		}

		$authInfo = $this->getInfoByName($_POST['user_name']);
		if ($authInfo === false){
			$this->error(L('login_wrong'));
		}
		$hash = $authInfo['user_password'];
		$password = $_POST['user_password'];
		if (!$this->checkPassword($password, $hash)) {
			$this->error(L('login_wrong'));
		} else {
			
			$_SESSION[C('USER_AUTH_KEY')]  =   $authInfo['user_id'];
			$_SESSION['user_name']         =   $authInfo['user_name'];
            $_SESSION['user_nickname']	   =   $authInfo['user_nickname'];
            $_SESSION['user_email']		   =   $authInfo['user_email'];
            $_SESSION['user_lastlogin']	   =   $authInfo['user_lastlogin'];
			$_SESSION['user_lastip']	   =   $authInfo['user_lastip'];
			$_SESSION['user_logincount']   =   $authInfo['user_logincount'];
			$_SESSION['user_status']       =   $authInfo['user_status'];
			$_SESSION['user_level']        =   $authInfo['user_level'];
			$_SESSION['user_logintime']    =   gmtime(); //登录时间

			//保存登录信息
			$user	=	M('AdminUser');
			$ip		=	get_client_ip();
			$time	=	gmtime();
			$data   =   array();
			$data['user_id']	     =	$authInfo['user_id'];
			$data['user_lastlogin']	 =	$time;
			$data['user_logincount'] =	array('exp','user_logincount+1');
			$data['user_lastip']	 =	$ip;
			$user->save($data);
			set_log('login(System)');
			$this->success(L('login_success'));
		}
	}
	
	//修改密码
	public function adminPwd() {
		$this->checkUser();
		$this->assign('action_link', array('href'=>__URL__.'/adminList/', 'text' => L('adminList')));
		$this->assign('ur_here',L('adminPwd'));
		$this->display();
	}
	
	public function changePwd() {
		$this->checkUser();
		$authInfo = $this->getInfoById($_SESSION[C('USER_AUTH_KEY')]);		
		$hash = $authInfo['user_password'];
		$password = $_POST['old_password'];
		if (!$this->checkPassword($password, $hash)) {
			$this->error(L('old_password_wrong'));
		} else {
			$admin	 =	 M("AdminUser");
			import("@.ORG.Phpass");
			$nb_hasher = new PasswordHash(8, true);	
			$admin->user_password = $nb_hasher->HashPassword($_POST['new_password']);
			$admin->save();
			set_log('password(User)');
			//$this->assign('jumpUrl',__APP__.'/Public/main/');
			/* 修改密码后应该重新登录 */
			unset($_SESSION);
			session_destroy();
			$this->assign('jumpUrl',__URL__.'/login/');
			$this->success(L('edit_password_success'));
         }
	}
	
	//编辑个人资料
	public function adminInfo() {
		$this->checkUser();
		$admin	 =	 M("AdminUser");
		$vo	=	$admin->getByUserId($_SESSION[C('USER_AUTH_KEY')]);
		$this->assign('vo',$vo);
		$this->assign('action_link', array('href'=>__URL__.'/adminList/', 'text' => L('adminList')));
		$this->assign('ur_here',L('adminInfo'));
		$this->display();
	}
	
	public function changeInfo() {
		$this->checkUser();
		$admin	=  D("AdminUser");
		if (false === $admin->create()) {
			$this->error($admin->getError());
		}
		$result  =  $admin->save();
		if (false !== $result) {
            $_SESSION['user_nickname']	   =	$_POST['user_nickname'];
            $_SESSION['user_email']		   =	$_POST['user_email'];
			set_log('profile(User)'); 
			//$this->assign('jumpUrl',__APP__);
			$this->assign('jumpUrl',__APP__.'/Public/main/');
			$this->success(L('edit_info_success'));
		} else {
			$this->error(L('error'));
		}
	}

	//日志列表
	public function adminLog() {
		$this->checkUser();
		//排序字段 默认为主键
		if (isset($_REQUEST ['order'])) {
			$order = $_REQUEST ['order'];
		} else {
			$order = 'log_id';
		}
		//排序方式 默认按照倒序排列
		if (isset($_REQUEST ['sort'])) {
			$sort = $_REQUEST ['sort'];
		} else {
			$sort = 'desc';
		}
		$map  =	 array();
		if ($_REQUEST['log_ip']!='') {
			$map['log_ip'] = $_REQUEST['log_ip'];
		}
		if ($_REQUEST['n']!='') {
			$map['user_name'] = $_REQUEST['n'];
		}	
		if (!empty($_REQUEST['key'])) {
			$map = json_decode(base64_url_decode($_REQUEST['key']));
		} 
		$log  =  D('AdminlogView');
		import("@.ORG.Page");
		C ( 'PAGE_ROLLPAGE',C('page_roll') );
		$count = $log->where($map)->count();
		$p = new Page ($count, C('admin_list_num'));
		$list = $log->where($map)->field('log_id,user_name,log_time,log_info,log_script,log_ip')->order("`".$order."` ".$sort)->limit($p->firstRow.','.$p->listRows)->findAll();
		$list_ip = $log->DISTINCT(true)->field('log_ip')->findAll();
		$p->setConfig('theme',C('admin_page_theme'));
		//分页跳转的时候保证查询条件
		/*foreach ($map as $key => $val) {
			if (!is_array ($val)) {
				$p->parameter .= "$key=" . urlencode ( $val ) . "&";
			}
		}*/
		
		if (!empty($map)) {
			$p->parameter .= "key=" . base64_url_encode(json_encode($map)) . "&";
		}
		
		$page = $p->show ();
	
		$this->assign('action_link', array('href'=>__URL__.'/adminList/', 'text' => L('adminList')));
		$this->assign('ur_here',L('adminLog'));
		$this->assign('pagestyle',C('admin_page_style'));
		$this->assign('page', $page);
		$this->assign('list',$list);
		$this->assign('sort',$sort);
		$this->assign('list_ip',$list_ip);
		$this->display();
	}

	
	//删除日志
	public function delLog() {
		$this->checkUser();
		$this->checkLimits();
		$log  =  M('AdminLog');
		$drop_type_date = isset($_POST['drop_type_date']) ? $_POST['drop_type_date'] : '';
		/* 按日期删除日志 */
		if ($drop_type_date) {	
			if ($_POST['log_time'] == '0') {
				redirect(__URL__.'/adminLog/');
				exit;
			} elseif ($_POST['log_time'] > '0') {
				$where = '';
				switch ($_POST['log_time']) {
					case '1':
						$a_week = gmtime()-(3600 * 24 * 7);
						$where .= "log_time <= '".$a_week."'";
						break;
					case '2':
						$a_month = gmtime()-(3600 * 24 * 30);
						$where .= "log_time <= '".$a_month."'";
						break;
					case '3':
						$three_month = gmtime()-(3600 * 24 * 90);
						$where .= "log_time <= '".$three_month."'";
						break;
					case '4':
						$half_year = gmtime()-(3600 * 24 * 180);
						$where .= "log_time <= '".$half_year."'";
						break;
					case '5':
						$a_year = gmtime()-(3600 * 24 * 365);
						$where .= "log_time <= '".$a_year."'";
						break;
				}
				$list = $log->where($where)->delete();
				if ($list!==false) {
					set_log('drop(Log, Date)');
					$this->assign('jumpUrl',__URL__.'/adminLog/');
					$this->success (L('success'));
				} else {
					$this->error (L('error'));
				}
			}	
		}else {
			$pk   =  $log->getPk();
			$condition = array ($pk => array ('in', $_POST['key']));
			$list = $log->where($condition)->delete();
			if ($list!==false) {
				set_log('drop(Log, Count: '.count($_POST['key']).')');
				$this->assign('jumpUrl',__URL__.'/adminLog/');
				$this->success (sprintf(L('batch_drop_success'), count($_POST['key'])));
			} else {
				//$this->assign('jumpUrl',__APP__);
				$this->error (L('error'));
			}
		}
	}
	
	//添加用户
	public function adminAdd() {
		$this->checkUser();
		$this->checkLimits();
		$this->assign('action_link', array('href'=>__URL__.'/adminList/', 'text' => L('adminList')));
		$this->assign('ur_here',L('adminAdd'));
		$this->display();
	}
	
	public function actionAdd() {
		$this->checkUser();	
		$this->checkLimits();	
		$admin = D('AdminUser');
		if (false === $admin->create()) {
			$this->error($admin->getError());
		} else {
			if ($result = $admin->add()) {
				set_log('add(User, Nickname: '.$admin->user_nickname.')');
				$this->assign('jumpUrl',__URL__.'/adminList/');
				$this->success(L('success'));
			} else {
				$this->error(L('error'));
			}
		}
	}
		
	//用户列表
	public function adminList() {
		$this->checkUser();
		$admin	 =	 M("AdminUser");
		$list	 =	$admin->select();
		$this->assign('list',$list);
		$this->assign('action_link', array('href'=>__URL__.'/adminAdd/', 'text' => L('adminAdd')));
		$this->assign('ur_here',L('adminList'));
		$this->display();
	}
	
	//用户编辑
	public function adminEdit() {
		$this->checkUser();
		$this->checkLimits();
		if ($_REQUEST['id'] == $_SESSION[C('USER_AUTH_KEY')]) {
			$this->error(L('edit_admininfo_cannot'));
		}
		$admin	 =	 M("AdminUser");
		$vo	=	$admin->getByUserId($_REQUEST['id']);
		$this->assign('vo',$vo);
		$this->assign('action_link', array('href'=>__URL__.'/adminList/', 'text' => L('adminList')));
		$this->assign('ur_here',L('adminEdit'));
		$this->display();
	}
	
	//用户编辑
	public function actionEdit() {
		$this->checkUser();
		$this->checkLimits();
		$admin = D('AdminUser');
		if (false === $admin->create()) {
			$this->error($admin->getError());
		} else {
			$result = $admin->save();
			if (false !== $result) {
				set_log('edit(User, Nickname: '.$admin->user_nickname.')');
				$this->assign('jumpUrl',__URL__.'/adminList/');
				$this->success(L('success'));
			} else {
				$this->error(L('error'));
			}
		}
	}
	
	//快速启用或禁用账号
	public function statusToggle() {
		$this->checkUser();
		$this->checkLimits();
		if ($_REQUEST['id'] == $_SESSION[C('USER_AUTH_KEY')]) {
			$this->error(L('edit_admininfo_cannot'));
		}
		$map	=	array();
		$map['user_id']	 =	$_REQUEST['id'];
		$status = ($_REQUEST['status'] == 0) ? 1 : 0;
		$admin = M('AdminUser');
		if ($list = $admin->where($map)->setField('user_status', $status)) {
			set_log('edit(User, Toggle, Id: '.$_REQUEST['id'].')');
			$this->assign('jumpUrl',__URL__.'/adminList/');
			$this->success(L('success'));
		} else {
			$this->error(L('error'));
		}
	}
	
	//验证码
	public function verify() {
		$type	 =	 isset($_GET['type'])?$_GET['type']:'gif';
		import("@.ORG.Image");
		Image::buildImageVerify(4,3,$type);
	}
	
	//空操作
	public function _empty() {
		$this->checkUser();
		$this->assign('jumpUrl',__APP__);
		$this->error(L('illegal'));
	}
	
	//通过登录名查询管理员信息
	public function getInfoByName($name) {
	    $admin = M('AdminUser');
	    $map['user_name'] = $name;
		$map['user_status']   = 1;
		if ($authInfo = $admin->where($map)->find()) {
			return $authInfo;
		} else {
			return false;
		}
	}
	
	//通过登录id查询管理员信息
	public function getInfoById($id) {
	    $admin = M('AdminUser');
	    $map['user_id'] = $id;
		$map['user_status']   = 1;
		if ($authInfo = $admin->where($map)->find()) {
			return $authInfo;
		} else {
			return false;
		}
	}
	
	//验证密码
	public function checkPassword($password, $hash) {
		global $nb_hasher;
		if (empty($nb_hasher)) {
			import("@.ORG.Phpass");
			$nb_hasher = new PasswordHash(8, true);
		}
		$check = $nb_hasher->CheckPassword($password, $hash);
		return $check;
	}
	
}

?>